package com.meituan.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Component
public class UploadUtils {
    @Value("${qiniu.key.access}")
    private String ak;
    @Value("${qiniu.key.secret}")
    private String sk;
    @Value("${qiniu.bucket.bucket.name}")
    private String bucket;
    @Value("${qiniu.bucket.header.url}")
    private String url;

    public String upload(MultipartFile multipartFile){
        Configuration cfg = new Configuration(Region.huabei());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String key = null;
        Auth auth = Auth.create(ak, sk);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(multipartFile.getInputStream(),key,upToken,null, null);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return url+putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
